/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.zx.user.vip.service;

import java.io.IOException;
import java.util.List;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.common.service.CrudService;
import com.jeesite.common.service.ServiceException;
import com.jeesite.common.utils.excel.ExcelImport;
import com.jeesite.common.validator.ValidatorUtils;
import com.jeesite.modules.zx.user.vip.entity.TuserVip;
import com.jeesite.modules.sys.entity.EmpUser;
import com.jeesite.modules.sys.service.EmpUserService;
import com.jeesite.modules.zx.question.bank.entity.TquestionBank;
import com.jeesite.modules.zx.user.vip.dao.TuserVipDao;

/**
 * 用户会员管理Service
 * @author zpp
 * @version 2020-03-22
 */
@Service
@Transactional(readOnly=true)
public class TuserVipService extends CrudService<TuserVipDao, TuserVip> {
	@Autowired
	private EmpUserService empUserService;
	/**
	 * 获取单条数据
	 * @param tuserVip
	 * @return
	 */
	@Override
	public TuserVip get(TuserVip tuserVip) {
		return super.get(tuserVip);
	}
	
	/**
	 * 查询分页数据
	 * @param tuserVip 查询条件
	 * @param tuserVip.page 分页对象
	 * @return
	 */
	@Override
	public Page<TuserVip> findPage(TuserVip tuserVip) {
		return super.findPage(tuserVip);
	}
	
	/**
	 * 保存数据（插入或更新）
	 * @param tuserVip
	 */
	@Override
	@Transactional(readOnly=false)
	public void save(TuserVip tuserVip) {
		super.save(tuserVip);
	}
	
	/**
	 * 更新状态
	 * @param tuserVip
	 */
	@Override
	@Transactional(readOnly=false)
	public void updateStatus(TuserVip tuserVip) {
		super.updateStatus(tuserVip);
	}
	
	/**
	 * 删除数据
	 * @param tuserVip
	 */
	@Override
	@Transactional(readOnly=false)
	public void delete(TuserVip tuserVip) {
		super.delete(tuserVip);
	}
	@Transactional(readOnly=false)
	public String importData(MultipartFile file, boolean isUpdateSupport) {
		if (file == null){
			throw new ServiceException(text("请选择导入的数据文件！"));
		}
		int successNum = 0; int failureNum = 0;
		StringBuilder successMsg = new StringBuilder();
		StringBuilder failureMsg = new StringBuilder();
		try(ExcelImport ei = new ExcelImport(file, 2, 0)){
			List<TuserVip> list = ei.getDataList(TuserVip.class);
			for (TuserVip entity : list) {
				try {
					String mobile = entity.getMobile();
					if(StringUtils.isNotBlank(mobile)){
						EmpUser empUser=new EmpUser();
						empUser.setMobile(mobile);
						List<EmpUser> findList = empUserService.findList(empUser);
						if(findList!=null&&findList.size()>0){
							entity.setUserId(findList.get(0).getUserCode());
						}else{
							continue;
						}
					}
					ValidatorUtils.validateWithException(entity);
					TuserVip u = get(entity.getId());
					if (u == null){
						entity.setIsNewRecord(true);
						this.save(entity);
						successNum++;
						successMsg.append("<br/>" + successNum + "、账号 " + entity.getId() + " 导入成功");
					} else if (isUpdateSupport){
						entity.setId(u.getId());
						this.save(entity);
						successNum++;
						successMsg.append("<br/>" + successNum + "、账号 " + entity.getId() + " 更新成功");
					} else {
						failureNum++;
						failureMsg.append("<br/>" + failureNum + "、账号 " + entity.getId() + " 已存在");
					}
				} catch (Exception e) {
					failureNum++;
					String msg = "<br/>" + failureNum + "、账号 " + entity.getId() + " 导入失败：";
					if (e instanceof ConstraintViolationException){
						ConstraintViolationException cve = (ConstraintViolationException)e;
						for (ConstraintViolation<?> violation : cve.getConstraintViolations()) {
							msg += Global.getText(violation.getMessage()) + " ("+violation.getPropertyPath()+")";
						}
					}else{
						msg += e.getMessage();
					}
					failureMsg.append(msg);
					logger.error(msg, e);
				}
			}
		} catch (Exception e) {
			failureMsg.append(e.getMessage());
			logger.error(e.getMessage(), e);
		}
		if (failureNum > 0) {
			failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
			throw new ServiceException(failureMsg.toString());
		}else{
			successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
		}
		return successMsg.toString();
	}
	
}